package com.org.msmvc.sys.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.org.util.FileUploadOrDown;
import com.org.util.excel.ExcelUtil;

/**
 * 上传文件到服务器
 * 
 * @author zsh
 * 
 */
@Controller
@RequestMapping("upOrDown")
public class FileUploadController {
	// 日志记录对象
	private Log log = LogFactory.getLog(this.getClass());
	
	@RequestMapping(value = "/query/{operate}")
	public ModelAndView execute(@PathVariable("operate") String operate,HttpServletRequest request,
			HttpServletResponse response) throws NumberFormatException, Exception {
		ModelAndView model = new ModelAndView();
		if (operate.equals("toUploadify")) {//进入上传列表
			model.setViewName("/uploadUtil");
		} 
		return model;
	}


	@RequestMapping(value = "/upload.do")
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,
			ModelMap model) {

		System.out.println("开始");
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		// String fileName = new Date().getTime()+".jpg";
		System.out.println(path);
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);

		return "result";
	}

	/**
	 * 上传图片到服务器
	 * 
	 * @return
	 */
	@RequestMapping("uplImg")
	@ResponseBody
	public Map<String, Object> uploadImg(String filename, MultipartHttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("success", false);
		try {

			MultipartFile file = request.getFile(filename);
			InputStream inputStream = file.getInputStream();
			String imgname = file.getOriginalFilename();
			FileUploadOrDown upimg = new FileUploadOrDown();
			// 存放图片位置
			Date now = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
			String name = sdf.format(now);
			String imgUrl = upimg.upToServer(name + imgname.substring(imgname.indexOf("."), imgname.length()), "temp",
					inputStream, "/erp/upload/imgs/");

			result.put("imgUrl", imgUrl);
			result.put("success", true);
		}  catch (Exception e) {
			e.printStackTrace();
			log.error("添加或修改用户商品信息" + e.getMessage(), e);
			result.put("msg", e.getMessage());
		}
		return result;
	}
	
	
	/**
	 * 图片上传
	 * @param
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 */
	 @RequestMapping(value = "/uploadify",method=RequestMethod.POST)
	    @ResponseBody
	    public void uploadHandlerForUploadify(HttpServletRequest request,HttpServletResponse response) throws URISyntaxException
	            {
		 response.setContentType("text/plain;charset=UTF-8");  
		 	String message="";
	        Integer userID = 0;
	        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	        Map<String,MultipartFile> fileMap=multipartRequest.getFileMap();
	      // String ctxpath =  request.getRealPath("/") +"/data/upload/"+request.getParameter("folders")+File.separator;//会直接存放到当前盘的根目录下
	       String path=this.getClass().getResource("/").toURI().getPath();
	       path = path.substring(0, path.length() - 17);
			path = path.substring(0,path.lastIndexOf("/")+1) ;
	        SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmSS");
	        String imgUrl= "upload/images/"+request.getParameter("folders")+"/";
	        File file=new File(path+imgUrl);
	        if(!file.exists()){
	        	file.mkdirs();
	        }
	        String fileName=null;
	        String filePath="";
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
	        String name = null;
	        for(Map.Entry<String,MultipartFile>entity:fileMap.entrySet()){
	        	MultipartFile mf=entity.getValue();//上传文件
	        	fileName=mf.getOriginalFilename();//源文件名字
				name=sdf.format(new Date());
				name=name + fileName.substring(fileName.indexOf("."),fileName.length());
	        	File uploadFile=new File(path+imgUrl+name);
	        	try {
					FileCopyUtils.copy(mf.getBytes(), uploadFile);
					//filePath=uploadFile.getPath();
					filePath="/"+imgUrl+name;
					message="上传成功";
				} catch (IOException e) {
					// TODO Auto-generated catch block
					message="上传失败";
					e.printStackTrace();
				}
	        	
	        }

	        try {
	        	response.setHeader("Content-type", "text/html;charset=UTF-8");  
		        response.setCharacterEncoding("UTF-8");
				response.getWriter().write(filePath);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	    } 
	 
	 
	 	@RequestMapping("/getImg")  
	    public void getImg(HttpServletRequest request, HttpServletResponse response) throws Exception{  
	        String file = request.getParameter("file");  
	       // String path = request.getSession().getServletContext().getRealPath("/")+"uploadFiles"+File.separator+file;
	        String path="d:/data/imgs/";
	        File pic = new File(path+file);  
	        FileInputStream fis = new FileInputStream(pic);  
	        OutputStream os = response.getOutputStream();  
	        try {  
	            int count = 0;  
	            byte[] buffer = new byte[1024 * 1024];  
	            while ((count = fis.read(buffer)) != -1)  
	                os.write(buffer, 0, count);  
	            os.flush();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } finally {  
	            if (os != null)  
	                os.close();  
	            if (fis != null)  
	                fis.close();  
	        }  
	          
	    }  
	 
		@RequestMapping(value ="/upUtils", method = RequestMethod.POST)  
		@ResponseBody
	    public Map upload(HttpServletRequest request,HttpServletResponse response) {
			Map<String, Object> map = new HashMap<String, Object>();
	        try {
	        	String ctxpath = "e:/upload1/";
	            // 设置传入的文件的编码
	            response.setCharacterEncoding("utf-8");
	            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		        Map<String,MultipartFile> fileMap=multipartRequest.getFileMap();
	            // 服务器目录
	            String targetDirectory = request.getSession().getServletContext().getRealPath("\\") + "upload\\";
	            // 设置上传文件的新文件名
	            String nowTime = new SimpleDateFormat("yyyymmddHHmmss")
	                    .format(new Date());// 当前时间
	            File file=new File(ctxpath);
		        if(!file.exists()){
		        	file.mkdirs();
		        }
		        String fileName=null;
		        String filePath="";
		        for(Map.Entry<String,MultipartFile>entity:fileMap.entrySet()){
		        	MultipartFile mf=entity.getValue();//上传文件
		        	fileName=mf.getOriginalFilename();//源文件名字
		        	File uploadFile=new File(ctxpath+fileName);
		        	try {
		        		// 文件已经存在删除原有文件
			            if (uploadFile.exists()) {
			            	uploadFile.delete();
			            }
						FileCopyUtils.copy(mf.getBytes(), uploadFile);
						filePath=uploadFile.getPath();
						System.out.println("-------------------"+filePath);
						int i=readUpExcle(uploadFile);//批量计算
						
						if(i>0){
							map.put("message","已成功计算完成"+i+"个");
							map.put("flag",true);
						}else{
							map.put("message","教练奖金计算失败");
							map.put("flag",false);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
		        	
		        }
	 
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return map;
	    }
	    
	    /**
	     * org.apache.commons  上传
	     * @param request
	     * @param response
	     * @throws Exception
	     */
	    public void doGet(HttpServletRequest request, HttpServletResponse response)
	            throws Exception {
	        request.setCharacterEncoding("utf-8");  //设置编码
	        //获得磁盘文件条目工厂
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        //获取文件需要上传到的路径
	       // String path = request.getRealPath("/upload1");
	      String path = "e:/upload1";
	        //如果没以下两行设置的话，上传大的 文件 会占用 很多内存，
	        //设置暂时存放的 存储室 , 这个存储室，可以和 最终存储文件 的目录不同
	        /**
	         * 原理 它是先存到 暂时存储室，然后在真正写到 对应目录的硬盘上， 
	         * 按理来说 当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的 
	         * 然后再将其真正写到 对应目录的硬盘上
	         */
	        factory.setRepository(new File(path));
	        //设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
	        factory.setSizeThreshold(1024*1024) ;
	        //高水平的API文件上传处理
	        ServletFileUpload upload = new ServletFileUpload(factory);
	        try {
	            //可以上传多个文件
	            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
	            for(FileItem item : list){
	                //获取表单的属性名字
	                String name = item.getFieldName();
	                //如果获取的 表单信息是普通的 文本 信息
	                if(item.isFormField()){
	                    //获取用户具体输入的字符串 ，名字起得挺好，因为表单提交过来的是 字符串类型的
	                    String value = item.getString() ;
	                    request.setAttribute(name, value);
	                }else{//对传入的非 简单的字符串进行处理 ，比如说二进制的 图片，电影这些
	                    /**
	                     * 以下三步，主要获取 上传文件的名字
	                     */
	                    //获取路径名
	                    String value = item.getName() ;
	                    //索引到最后一个反斜杠
	                    int start = value.lastIndexOf("\\");
	                    //截取 上传文件的 字符串名字，加1是 去掉反斜杠，
	                    String filename = value.substring(start+1);
	                    request.setAttribute(name, filename);
	                    //真正写到磁盘上
	                    //它抛出的异常 用exception 捕捉
	                    //item.write( new File(path,filename) );//第三方提供的
	                    //手动写的
	                    OutputStream out = new FileOutputStream(new File(path,filename));
	                    InputStream in = item.getInputStream() ;
	                    int length = 0 ;
	                    byte [] buf = new byte[1024] ;
	                    System.out.println("获取上传文件的总共的容量："+item.getSize());
	                    // in.read(buf) 每次读到的数据存放在   buf 数组中
	                    while( (length = in.read(buf) ) != -1){
	                        //在   buf 数组中 取出数据 写到 （输出流）磁盘上
	                        out.write(buf, 0, length);
	                    }
	                    in.close();
	                    out.close();
	                }
	            }
	        }catch (Exception e) {
	            e.printStackTrace();
	        }
	        request.getRequestDispatcher("filedemo.jsp").forward(request, response);
	    }
	    
	  
	    
	    
	    /**
	     * 读取服务器上excle中的值
	     * @param file
	     * @return
	     */
	    public int readUpExcle(File file) {
	    	DecimalFormat df = new DecimalFormat("#");
	    	int counts=0;
	    Workbook wb = null;
	    Sheet sheet = null;
	    String value = null;
	    Row row = null;// 表格行
	    List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
	    String msg = null;// 返回消息
	    int count = 0;// 成功上传条数
	    try {
	        // 将文件转成文件输入流
	        InputStream is = new FileInputStream(file);
	        // 判断Excel版本
	        if (file.getName().toUpperCase().endsWith(".XLSX")) {
	            wb = new XSSFWorkbook(is);// Excel 2007
	        } else {
	            wb = new HSSFWorkbook(is);// Excel 2003
	        }
	        FormulaEvaluator evaluator = wb.getCreationHelper()
	                .createFormulaEvaluator();// 解析公式结果
	        // 获得第一个表格页
	        sheet = wb.getSheetAt(0);
	        System.out.println(sheet.getLastRowNum() + "记录长度");
	        Map map=null;
	        // 遍历数据
	        for (int j = 1; j <= sheet.getLastRowNum(); j++) {
	        	StringBuilder sb = new StringBuilder();
	            // 获取某一行
	            row = sheet.getRow(j);
	            short minColIx = row.getFirstCellNum();  //第一列
	            short maxColIx = row.getLastCellNum(); //最后一列
	            map=new HashMap<String, Object>();
	            for(int i=0;i<maxColIx;i++){//迭代循环出每列的值
	            	Cell cell = row.getCell(i);  
	                CellValue cellValue = evaluator.evaluate(cell);
	                if (cellValue == null) {  
	                    continue;  
	                }
	                switch (cellValue.getCellType()) {  
	                case Cell.CELL_TYPE_BOOLEAN:  
	                	value =String.valueOf(cellValue.getBooleanValue());  
	                    break;  
	                case Cell.CELL_TYPE_NUMERIC:  
	                    // 这里的日期类型会被转换为数字类型，需要判别后区分处理  
	                    if (DateUtil.isCellDateFormatted(cell)) {  
	                    	value = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());  
	                    } else {  
	                    	value =String.valueOf(df.format(cellValue.getNumberValue()));  
	                    }  
	                    break;  
	                case Cell.CELL_TYPE_STRING:  // 字符串
	                	value = cellValue.getStringValue();  
	                    break;  
	                case Cell.CELL_TYPE_FORMULA:
	                	value =cell.getCellFormula();
	                    break;  
	                case Cell.CELL_TYPE_BLANK:  
	                	value = "";
	                    break;  
	                case Cell.CELL_TYPE_ERROR:
	                	value =String.valueOf(cell.getErrorCellValue());
	                    break;  
	                default:  
	                    break; 
	                }  
	                if(i==1){
	                	
	                	map.put("idcard", value.trim());
	                }
				    if(i==2){
				    	map.put("phone", value.trim());      	
				                    }
				    if(i==3){
				    	map.put("passtime", value.trim());       	
				                    }
	            }
	            list.add(map);
	            System.out.println("------"+sb.toString());
	            count++;

	        }
	        msg = "数据上传成功,一共上传" + count + "条!";
	        
	        /*保存数据到数据库begin*/
			for(Map<String, Object>entity:list){
				if(entity.isEmpty()){
					continue;
				}
			
			}
			 /*保存数据到数据库 end*/
	    } catch (Exception e) {
	        e.printStackTrace();
	        msg = e.getMessage();
	    }
	    return counts;
	}

	@RequestMapping(value="/download")
	public String downFile(@RequestParam("fileName") String fileName,HttpServletRequest request, HttpServletResponse response)throws Exception{
		if (fileName != null) {
			//String realPath = "";//request.getServletPath().getRealPath("WEB-INF/template/");
			String realPath =request.getSession().getServletContext().getRealPath("WEB-INF/template/");
			File file = new File(realPath, fileName);
			if (file.exists()) {
				//response.setContentType("application/force-download");// 设置强制下载不打开
				//response.addHeader("Content-Disposition","attachment;fileName=" + fileName);// 设置文件名

				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO_8859_1") );// 设定输出文件头
				response.setContentType("application/vnd.ms-excel;charset=utf-8");

				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					os.close();
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					if (bis != null) {
						try {
							  bis.close();
						      } catch (IOException e) {
							                             // TODO Auto-generated catch block
							        e.printStackTrace();
						}
					}
					if (fis != null) {
						 try {
							     fis.close();
							} catch (IOException e) {
							    // TODO Auto-generated catch block
							   e.printStackTrace();
							}
					}
				}

			}
		}
	    	return null;
	}
	public static void main(String args[]) {
		try {
			File file = null;
			String path = FileUploadController.class.getClass().getResource("/").getPath();
			ClassLoader classloader = Thread.currentThread().getContextClassLoader();
			file = new File(classloader.getResource("WEB-INF/template/教练绩效模版.xls").getFile());

			System.out.println("mysql_url="+file.getName());
			/*path = path.substring(1, path.indexOf("classes"));
			//读出具体的参数
			System.out.println("mysql_url="+path);*/


		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
